package com.cacho.s2b.lesson.learn;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;

import java.math.BigDecimal;

/**
 * @Description com.jayway.jsonpath
 * @Author LingWei
 * @date 2024/1/23
 **/
public class LearnJsonpath {
    public static void main(String[] args) throws Exception {
        String jPath = "$.Data.AccountId"; // 字符串：01700020402SAR
        String floatPath = "$.Data.Transaction[0].Amount.Amount"; // 金额：100
        String jsonStr = "{\"Links\":{\"Self\":\"http://ms-accounts-openapi-pilot-nonssl-api-banking-sit.apps.dcda-np2.ocp.dev.net/openapi/accounts/v3/01700020402SAR/transactions\"},\"Meta\":{\"page\":1,\"size\":1,\"total\":1},\"Data\":{\"AccountId\":\"01700020402SAR\",\"Transaction\":[{\"TransactionReference\":\"0000155\",\"TransactionDateTime\":\"2024-01-10T00:00:00+03:00\",\"BookingDateTime\":\"2024-01-10T00:00:00+03:00\",\"ValueDateTime\":\"2024-01-10T00:00:00+03:00\",\"DebtorAgent\":{\"Identification\":\"SCBLSAR0XXX\",\"IdentificationType\":\"KSAOB.BICFI\",\"Name\":\"\",\"PostalAddress\":{\"AddressType\":\"\",\"ShortAddress\":\"\",\"BuildingNumber\":\"\",\"UnitNumber\":\"\",\"StreetName\":\"\",\"SecondaryNumber\":\"\",\"District\":\"\",\"PostalCode\":\"\",\"City\":\"\",\"Country\":\"\"}},\"Amount\":{\"Amount\":100.00,\"Currency\":\"SAR\"},\"CreditDebitIndicator\":\"KSAOB.Debit\",\"TransactionId\":\"202012280003360\",\"ProprietaryBankTransactionCode\":{\"Code\":\"703\",\"Issuer\":\"BAI\"},\"TransactionInformation\":\"COMMISSION INVOICE FINANCING SUPPLIER-OTH\",\"TransactionType\":\"KSAOB.Other\",\"SubTransactionType\":\"KSAOB.NotApplicable\",\"PaymentModes\":\"KSAOB.Online\",\"Status\":\"KSAOB.Booked\",\"BankTransactionCode\":{\"Family\":\"\",\"FamilyCode\":\"\",\"SubFamily\":\"\",\"SubFamilyCode\":\"\"},\"LocalTimeZone\":\"\",\"StatementReference\":\"\",\"TerminalId\":\"\",\"Flags\":\"\",\"TransactionMutability\":\"\",\"ChargeAmount\":{\"Amount\":\"\",\"Currency\":\"\"},\"ChargeAmountVat\":{\"Amount\":\"\",\"Currency\":\"\"},\"CurrencyExchange\":{\"SourceCurrency\":\"\",\"TargetCurrency\":\"\",\"UnitCurrency\":\"\",\"QuotationDate\":\"\",\"InstructedAmount\":{\"Amount\":\"\",\"Currency\":\"\"}},\"MerchantDetails\":{\"MerchantId\":\"\",\"MerchantName\":\"\",\"MerchantCategoryCode\":\"\"},\"CreditorAgent\":{\"IdentificationType\":\"\",\"Identification\":\"\",\"Name\":\"\",\"PostalAddress\":{\"AddressType\":\"\",\"ShortAddress\":\"\",\"BuildingNumber\":\"\",\"UnitNumber\":\"\",\"StreetName\":\"\",\"SecondaryNumber\":\"\",\"District\":\"\",\"PostalCode\":\"\",\"City\":\"\",\"Country\":\"\"}},\"CreditorAccount\":{\"IdentificationType\":\"\",\"Identification\":\"\",\"Name\":\"\"},\"DebtorAccount\":{\"IdentificationType\":\"\",\"Identification\":\"\",\"Name\":\"\"},\"CardInstrument\":{\"CardSchemeName\":\"\",\"InstrumentType\":\"\",\"Name\":\"\",\"Identification\":\"\"},\"SupplementaryData\":\"\",\"BillDetails\":{\"BillerId\":\"\",\"BillNumber\":\"\",\"BillPaymentType\":\"\"}}]}}";
        Object obj = JsonPath.read(jsonStr, jPath);
        System.out.println("json解析对象值：" + obj);
        Object objFloat = JsonPath.read(jsonStr, floatPath);
        System.out.println("json解析float对象值：" + new BigDecimal(objFloat + ""));
        System.out.println("json获取对象值：" + readToString(jsonStr, jPath));
        System.out.println("json删除对象：" + delete(jsonStr, "$.Data.Transaction"));
        System.out.println("json更新对象：" + setByPath(jsonStr, "$.Data.AccountId","add"));
    }

    public static String readToString(String jsonStr, String jsonPath) {
        String retString = "";
        Object obj = JsonPath.read(jsonStr, jsonPath);
        if (obj != null) {
            retString = switch (obj.getClass().getTypeName()) {
                case "java.lang.Double", "java.lang.Float", "java.lang.Long" ->
                        String.valueOf(new BigDecimal(obj + ""));
                default -> String.valueOf(obj);
            };
        }
        return retString;
    }

    public static String delete1(String jsonStr, String jsonPath) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(jsonStr);
        rootNode = JsonPath.parse(rootNode).delete(JsonPath.compile(jsonPath)).json();
        return mapper.writeValueAsString(rootNode);
    }

    public static String delete(String jsonStr, String jsonPath) {
        DocumentContext jsonContext = JsonPath.parse(jsonStr);
        jsonContext.delete(jsonPath);
        return jsonContext.jsonString();
    }

    public static String setByPath(String jsonStr,String jsonPath,Object value){
        DocumentContext jsonContext = JsonPath.parse(jsonStr);
        jsonContext.set(jsonPath,value);
        return jsonContext.jsonString();
    }
}